package com.example.test;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    Button bind , unbind , getServiceStatus;
    //保持启动的Service的IBinder对象
    BindService.MyBinder binder;
    //定义一个ServiceConnection对象
    private ServiceConnection conn = new ServiceConnection() {
        //获取Service的onBind方法所返回的MyBinder对象
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (BindService.MyBinder) service; }
        //当该activity与Service断开时连接回调方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("Service Disconnected");
        }
    };
    @Override
    public  void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取程序界面中的start、stop、getServiceStatus按钮
        bind =(Button) findViewById(R.id.bind);
        unbind = (Button) findViewById(R.id.unbind);
        getServiceStatus=(Button) findViewById(R.id.getServiceStatus);

        //创建启动Service的intent

        //final Intent intent = new Intent();
        //intent.setAction("Bind_Service");
        final Intent intent = new Intent(MainActivity.this,BindService.class);

        bind.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View v) {
                //绑定指定Service
                Toast.makeText(MainActivity.this
                        , "已绑定"
                        , 2000).show();
                System.out.println("Service Connected");
                bindService(intent, conn, Service.BIND_AUTO_CREATE);
            }
        });
        unbind.setOnClickListener(new View.OnClickListener()
        {
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View source)
            {
                Toast.makeText(MainActivity.this
                        , "解除绑定"
                        , 2000).show();
                //解除绑定Service
                unbindService(conn);
            }
        });
        getServiceStatus.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View v) {
                // 获取、并显示Service的count值
                Toast.makeText(MainActivity.this
                        , "Serivce的count值为：" + binder.getCount()
                        , 4000).show();
            }
        });


    }}